const cloud = require('wx-server-sdk')

cloud.init()

/// (id: PoolId, user: UserId) => (StatusCode)
/// StatusCode:

const SUCCESS = 0;
const BAD_PARAM = -1;
const NOT_FOUND = -2;
const MAX_BORROW_COUNT_EXCEEDED = -3;

const MONTH_OFFSET = 30 * 24 * 60 * 60 * 1000;

exports.main = async (event) => {
  const db = cloud.database();
  const id = event.id;
  const user = event.user;
  
  if (id == null || user == null) {
    return {
      result: BAD_PARAM
    };
  }

  const pooledBook = await db.collection('pool').doc(id).get();
  const user = await db.collection('users').doc(user).get();

  if (pooledBook == null || user == null) {
    return {
      result: NOT_FOUND
    };
  }

  const borrowCount = await db.collection('records').aggregate().match({
    openid: user.openid,
    isOpen: true
  }).count();

  if (borrowCount >= user.maxBorrowCount) {
    return {
      result: MAX_BORROW_COUNT_EXCEEDED
    };
  }

  const record = {
    borrowTime: Date.now(),
    expectedReturnTime: Date.now() + MONTH_OFFSET,
    openid: user.openid,
    isOpen: true,
    book: pooledBook.book
  };

  await db.collection('pool').doc(id).remove();
  const res = await db.collection('record').add({
    data: record
  });

  return {
    code: SUCCESS,
    result: res._id
  };
}
